package pl.un4giv3n.mightvsmagic.action.clan;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;

public class RemoveUserFromClanAction extends ClanAction {

	private static final long serialVersionUID = 1L;
	private Long userId;
	private User selectedUser;

	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		clan = user.getClan();
		if (clan == null || !isClanAdmin()) {
			entityManager.close();
			addActionError("Wybrany klan nie istnieje lub niewystarczające uprawnienia.");
			return INPUT;
		} else if (userId != null && entityManager.find(User.class, userId) != null) {
			selectedUser = entityManager.find(User.class, userId);
			EntityTransaction transaction = entityManager.getTransaction();
			transaction.begin();
			selectedUser.setClanRank("");
			selectedUser.setClanAdmin(false);
			selectedUser.setClanMod(false);
			selectedUser.setClan(null);
			clan.getUsers().remove(selectedUser);
			entityManager.merge(selectedUser);
			entityManager.merge(clan);
			UserActivity activity = ActivityLogUtil.createActivity(ActivityType.REMOVE_USER_FROM_CLAN, user.getId(), "Usunięcie z klanu gracza="+selectedUser);
			entityManager.persist(activity);
			entityManager.flush();
			transaction.commit();
			entityManager.close();
			return SUCCESS;
		} else{
			entityManager.close();
			addActionError("Wybrany użytkownik nie istnieje");
			return INPUT;
		}
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public User getSelectedUser() {
		return selectedUser;
	}

	public void setSelectedUser(User selectedUser) {
		this.selectedUser = selectedUser;
	}
}
